package com.ruiyian.netty.DataUtils;

import com.aliyun.outboundbot20191226.models.AssignJobsResponse;
import com.aliyun.outboundbot20191226.models.DescribeJobResponse;
import com.aliyun.outboundbot20191226.models.DescribeJobResponseBody;
import com.aliyun.tea.TeaException;
import com.ruiyian.system.domain.ServerPointFormal;
import com.ruiyian.system.mapper.ServerPointMapper;
import com.ruiyian.system.service.ServerPointService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class OutboundUtils {
    @Autowired
    private ServerPointMapper serverPointService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void test(){
        List<ServerPointFormal> serverPointFormalList = serverPointService.getserverpoint(1);
        System.out.println(serverPointFormalList);
    }
    // 根据条件进行电话报警
    public int alarmPushByConditions(String tunnelName, String clientId, Map<String,String> deviceInfo, ServerPointFormal serverPointFormal) throws Exception {
        // 复用sys_user数据库存储报警电话
        String sql = "SELECT phonenumber from sys_user WHERE user_name='admin'";
        List<Map<String, Object>> phoneNumList =  jdbcTemplate.queryForList(sql);
        String phoneNum = (String) phoneNumList.get(0).get("phonenumber");
        String alarmFlag = serverPointFormal.getAlarm_flag();
        int alarmNum = serverPointFormal.getAlarm_num();
        if(alarmFlag.equals("1")){
            if(alarmNum<=2){
                // 如果是还没有报警过
                if(serverPointFormal.getJob_id()==null||serverPointFormal.getJob_id().equals("0")){
                    for (String key : deviceInfo.keySet()) {
                        String devStatus = deviceInfo.get(key);
                        if(!devStatus.equals("正常") && key!="waterPressure"){
                            String jobId = alarmPush(tunnelName, clientId, DataUtils.devEntoChinese(key), devStatus, phoneNum);
                            if(jobId.equals("101")){
                                return 101;
                            }
                            alarmNum++;
                            serverPointFormal.setJob_id(jobId);
                            serverPointFormal.setAlarm_num(alarmNum);
                            serverPointService.updateServerPoint(serverPointFormal);
                            return 0;
                        }
                        else {
                            continue;
                        }
                    }
                }
                // 如果已经是报警过了
                else {
                    // 获取这个点位电话报警的状态
                    DescribeJobResponseBody describeJobResponseBody = getJobInfo("5e961eee-accf-458c-83a4-8fae27d7d790", serverPointFormal.getJob_id());
                    // 如果是失败状态，则重播一次
                    if(describeJobResponseBody.job.status.equals("Failed")){
                        for (String key : deviceInfo.keySet()) {
                            String devStatus = deviceInfo.get(key);
                            String jobId = alarmPush(tunnelName, clientId, DataUtils.devEntoChinese(key), devStatus, phoneNum);
                            if(jobId.equals("101")){
                                return 101;
                            }
                            alarmNum++;
                            serverPointFormal.setJob_id(jobId);
                            serverPointFormal.setAlarm_num(alarmNum);
                            serverPointService.updateServerPoint(serverPointFormal);
                            return 0;
                        }
                    }
                    else {
                        return 6;
                    }
                }
            }
            else {
                return 7;
            }
        }
        else {
            return 8;
        }
        return 9;
    }

    public DescribeJobResponseBody getJobInfo(String instanceId, String jobId) throws Exception {
        DescribeJobResponse describeJobResponse = new DescribeJobResponse();
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
            // 必填，您的 AccessKey ID
            .setAccessKeyId("LTAI5t8hHXoMHNqvedtxd4To")
            // 必填，您的 AccessKey Secret
            .setAccessKeySecret("m7NdrqX2Kq53rBFduGQHWsYVhSFKRx");
        // Endpoint 请参考 https://api.aliyun.com/product/OutboundBot
        config.endpoint = "outboundbot.cn-shanghai.aliyuncs.com";
        com.aliyun.outboundbot20191226.Client client= new com.aliyun.outboundbot20191226.Client(config);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        com.aliyun.outboundbot20191226.models.DescribeJobRequest describeJobRequest = new com.aliyun.outboundbot20191226.models.DescribeJobRequest()
            .setInstanceId(instanceId)
            .setJobId(jobId);
        try {
            describeJobResponse = client.describeJobWithOptions(describeJobRequest, runtime);
            return describeJobResponse.body;
        } catch (TeaException error) {
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
            return describeJobResponse.body;
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
            return describeJobResponse.body;
        }
    }

    public String alarmPush(String tunnelName, String stakeMark, String devName, String status, String phoneNum) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
            // 必填，您的 AccessKey ID
            .setAccessKeyId("LTAI5t8hHXoMHNqvedtxd4To")
            // 必填，您的 AccessKey Secret
            .setAccessKeySecret("m7NdrqX2Kq53rBFduGQHWsYVhSFKRx");
        // Endpoint 请参考 https://api.aliyun.com/product/OutboundBot
        config.endpoint = "outboundbot.cn-shanghai.aliyuncs.com";
        com.aliyun.outboundbot20191226.Client client= new com.aliyun.outboundbot20191226.Client(config);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        com.aliyun.outboundbot20191226.models.AssignJobsRequest assignJobsRequest = new com.aliyun.outboundbot20191226.models.AssignJobsRequest().setJobGroupId("f2b85d27-5d17-4464-abae-32e7b1aa4d2f")
            .setInstanceId("5e961eee-accf-458c-83a4-8fae27d7d790")
            .setJobsJson(java.util.Arrays.asList("{\n" +
                "    \"extras\":[\n" +
                "        {\n" +
                "            \"value\":\"" +  tunnelName +"\",\n" +
                "            \"key\":\"tunnelName\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"value\":\"" +  stakeMark +"\",\n" +
                "            \"key\":\"stakeMark\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"value\":\"" +  devName +"\",\n" +
                "            \"key\":\"devName\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"value\":\"" +  status +"\",\n" +
                "            \"key\":\"status\"\n" +
                "        }\n" +
                "    ],\n" +
                "    \"contacts\":[\n" +
                "        {\n" +
                "            \"phoneNumber\":\"" + phoneNum + "\",\n" +
                "            \"name\":\"张三\",\n" +
                "            \"referenceId\":\"2c9a9a7c6caedab6016cb1ddd13325ed\",\n" +
                "            \"honorific\":\"张先生\"\n" +
                "        }\n" +
                "    ]\n" +
                "}"));
        try {
            // 复制代码运行请自行打印 API 的返回值
            AssignJobsResponse response = client.assignJobsWithOptions(assignJobsRequest, runtime);
            return  response.body.jobsId.get(0);
        } catch (TeaException error) {
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
            return "101";
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
            return "101";
        }
    }
}
